package linked;

import linked.base.ListNode;

public class Solution_148 {
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode middle = findMiddle(head);
        ListNode nextOfMiddle = middle.next;
        middle.next = null; // Split the list into two halves
        ListNode left = sortList(head);
        ListNode right = sortList(nextOfMiddle);
        return mergeTwoLists(left, right);
    }

    private ListNode findMiddle(ListNode head) {
        ListNode firNode = new ListNode();
        firNode.next = head;
        ListNode slow = firNode, fast = firNode;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode firNode = new ListNode();
        ListNode curNode = firNode;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                curNode.next = list1;
                list1 = list1.next;
                curNode = curNode.next;
            } else {
                curNode.next = list2;
                list2 = list2.next;
                curNode = curNode.next;
            }
        }
        if (list1 == null) {
            curNode.next = list2;
        } else {
            curNode.next = list1;
        }
        return firNode.next;
    }


}
